package com.suapi.suapigateway.task;

import com.suapi.suapicommon.model.constant.CommonConstant;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Slf4j
@Component
public class CacheTask {

    // 这里用Autowired不行
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public static final Long FIVE_MINUTES = 5 * 60L;


    // 每一分钟执行一次，清除redis 中过期的nonce
    //@Scheduled(cron="* * *  * * * ")
    @Scheduled(cron = "0 * * * * ? ")
    public void deleteExpireCache() {
        log.info("Task begin ...");
        // 没有key，直接返回
        if (!Boolean.TRUE.equals(redisTemplate.hasKey(CommonConstant.NONCE_KEY))){
            return;
        }
        ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
        // 获取所有元素及其分数（升序）
        Set<ZSetOperations.TypedTuple<Object>> tuples = zSetOps.rangeWithScores(CommonConstant.NONCE_KEY, 0, -1);
        //遍历每个元素
        if (tuples != null) {
            for (ZSetOperations.TypedTuple<Object> tuple : tuples) {
                Object value = tuple.getValue();   // 元素值
                Double score = tuple.getScore();   // 分数
                //判断随机数是否过期，及判断该随机数是否超过5分钟
                System.out.println("Value: " + value + ", Score: " + score);
                if (score != null && score < System.currentTimeMillis() / 1000 - FIVE_MINUTES) {
                    // 删除过期的元素
                    zSetOps.remove(CommonConstant.NONCE_KEY, value);
                    log.info("deleteExpireCache: {}", value);
                }
            }
        }
        log.info("Task end ...");
    }

}